#!/usr/bin/python
#
# Copyright (C) 2009 rambla.be
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Script that demonstrates how to configure a Wowza RTP live-stream.
"""

import time, socket, sys
import rawsc
import rawsc.service
from rawsc import rase
import rawsc.rase.service
try:
  from xml.etree import cElementTree as ElementTree
except ImportError:
  try:
    import cElementTree as ElementTree
  except ImportError:
    from elementtree import ElementTree

USER = "" # your username
PWD = "" # your pwd
SERVER = "rase.str01.rambla.be"

RASE_SDP_FILENAME = "" # name we're giving to the .sdp file on the streaming server (e.g. 'test.sdp')

# TODO: implement this method
def CREATE_LOCAL_SDP_FILE(portnrs, broadcast_ip):
    """ Method that creates an sdp file and returns its local path. 
    
        @param string of comma separated portnumbers reserved for this livestream
        @param IP Address of the broadcast server
        @return path to the created sdp file
    """
    ...
    # Make your own sdp file here
    return path_to_local_sdp_file


try:
    wowapp_entry = None
    # Create a RASE instance, passing it your login credentials and the base service uri
    client = rawsc.rase.service.RaseService(username=USER, password=PWD, server=SERVER)
    
    # retrieve the wowapp of type "rtp-live" that we'll be using for streaming
    # ------------------------------------------------------------------------
    qry = rawsc.Query()
    qry["type"] = "rtp-live"
    wowapp_feed = client.getWowappFeed(query = qry)
    for e in wowapp_feed.entry:
        wowapp_entry = e
        break
    
    if not wowapp_entry:
        print "Failed to retrieve wowapp entry of the given type."
        sys.exit(1)
    else:    
        print "\nRetrieved wowza app:"
        print "\Wowapp Entry URI: " + str(wowapp_entry.id.text)
        print "id: " + str(wowapp_entry.content.params.id.text)                        # id of this resource
        print "description: " + str(wowapp_entry.content.params.description.text)      # optional (informational purposes only)
        print "stream_type: " + str(wowapp_entry.content.params.stream_type.text)      # wowza stream type (e.g. 'rtp-live')
        print "stream_uri: " + str(wowapp_entry.content.params.stream_uri.text)        # URI to the wowza application on the edge servers (rtmp://)
        print "master_uri: " + str(wowapp_entry.content.params.master_uri.text)        # URI to the wowza application on the origin server (rtmp://)
        print "broadcast_domain: " + str(wowapp_entry.content.params.broadcast_domain.text)
        print "broadcast_ip: " + str(wowapp_entry.content.params.broadcast_ip.text)

    # claim 4 ports from RASE
    # ---------------------
    port_entry = client.createPort(nr_of_ports = "4") 
    print "\nReserved port-numbers for stream: " +  str(port_entry.content.params.portnrs.text) 

    # create/export local sdp file
    # ----------------------------
    # create a local sdp file with audio/video port numbers + broadcast IP Address (= FUNCTION NOT PART OF RASE CLIENT, need to write it yourself)
    path_to_local_sdp_file = CREATE_LOCAL_SDP_FILE(portnrs= port.content.params.portnrs.text, broadcast_ip=wowapp_entry.content.params.broadcast_ip.text)

    # create wowsdp resource
    #-----------------------
    # upload the wowsdp file, creating a "wowsdp" instance
    wowsdp_entry = client.createWowsdp(filename = RASE_SDP_FILENAME, local_path = path_to_local_sdp_file)
    # update wowsdp resource with required properties
    wowsdp_entry.content.params.port.text = port_entry.content.params.id.text # pass the ID of the port resource that has been created previously
    wowsdp_entry.content.params.wowapp.text = wowapp_entry.content.params.id.text
    wowsdp_entry.content.params.ip_address.text = socket.gethostbyname(socket.gethostname()) # pass the IP address of the encoder (alternatively set wowsdp_entry.content.params.mac_address.text)
    wowsdp_entry.content.params.description.text = "Testing" # optional description
    wowsdp_entry = client.updateWowsdp(entry = wowsdp_entry)    
    # config is now complete, use response data to start broadcasting
    if int(wowsdp_entry.content.params.status.text):
        print "\n\nCreated wowsdp resource:"
        print "broadcast_ip: " + str(wowsdp_entry.content.params.broadcast_ip.text)
        print "port id: " + str(wowsdp_entry.content.params.port.text)
        print "stream_loc: " + str(wowsdp_entry.content.params.stream_loc.text)        # relative location of the .sdp file on the streaming svr
        print "stream_uri: " + str(wowsdp_entry.content.params.stream_uri.text)        # URI to the wowza application on the edge servers (rtmp://)
        print "master_uri: " + str(wowsdp_entry.content.params.master_uri.text)        # URI to the wowza application on the origin server (rtmp://)
        
except rawsc.service.Error, e:
    print "Error Response from server, contents = %s.\n" % str(e)
    error_dict = e[0] # error dict inside the first tuple elem
    print "status code : " + str(error_dict["status"]) + "\n"
    if error_dict.has_key("body"):
        print "error body : " + error_dict["body"] + "\n"
except rawsc.RawscException, e:
    print "RawscException caught, reason = %s.\n" % str(e)
except StandardError, e:
    print "StandardError caught, reason = %s.\n" % str(e)
except:
    print "unhandled exception caught\n"
